<?php
/**
 * This is where PayPal customers land after purchasing.
 *
 * if they are logged in, look for their memberships
 * verifysign=
 *
 * we're passing the session id through and expect this to match, when it does, we add the membership
 * if users don't have an account yet, here is where they create one by filling in 3 form fields
 *
 */

include('HTGPage.class.php');
sleep(5);
$page = new HTGPage();
/* @var $utils Utils */
$utils = $page->myUtils;
$authKey = session_id();

//get the most recent PurchaseAttempt with pa_status = 'p'
$purchaseAttempts = $utils->getPurchaseAttempts($authKey, 'p', 'Completed');

if(count($purchaseAttempts) > 0 ) {
	//get the first one -- should be most recent
	$purchaseAttempt = $purchaseAttempts[0];

	//signing up after paypal purchase.verify registration
	$myEmail = strtolower($_REQUEST['pplRegEmail']);
	$myPassword = $_REQUEST['pplRegPassword1'];
	$myPasswordConfirm = $_REQUEST['pplRegPassword2'];
	$errorArray = array();
	$displayForm=true;

	if(!(empty($myPasswordConfirm))) {
		//is valid email
		if($utils->validEmail($myEmail)) {
			//does username exist
			$userRecords = $utils->getUser($myEmail);
			if(count($userRecords)) {
				//TODO  if they entered in the right password, log them in.
				//USER ALREADY FOUND
				if(!($page->login($myEmail, $myPassword))) {
					array_push($errorArray, "That email address is already taken.  Please use the \"Existing Account\" section to type in your current email and password.");
					$displayForm=true;
				}
			} else { //USER NOT FOUND OK TO ADD
				//do passwords match
				if(!empty($myPassword) && $myPassword == $myPasswordConfirm) {
					//add user
					$userId = $utils->addUser($myEmail, $myPassword); //should return id

					if(!($userId)) {
						error_log(__FILE__ . ':' . __LINE__ . "There was an issue when trying to add the user. USER INSERT FAILURE");
						array_push($errorArray, "For some reason we couldn\'t add a user.");
						$displayForm=true;
					} else { //end if user insert failure  Users INSERT SUCCESS
						$displayForm=false;
						if(!($page->login($myEmail, $myPassword))) {
							//THIS SHOULD ALWAYS WORK
							//logging the user in DIRTY
							$_SESSION['login_email'] = $myEmail;
							$_SESSION['u_id'] = $userId;
						}
					} //end else if user added successfully
				} else { //end password matching and user adding
					array_push($errorArray, 'Your passwords didn\'t match.  It\'s OK, just try again.' );
					$displayForm=true;
				}  //end passwords not matching
			} //end else user not found

		} else { //end isvalidemail
			array_push($errorArray, 'Your email address wasn\'t valid.  It\'s OK, just try again.' );
			$displayForm=true;
		}

	}

	if ($displayForm) {
		foreach($errorArray as $error) {
			$page->content .= '<span class="error">' . $error . '</span>';
		}
		$page->content .= '<h1>Create Account Now</h1>';
		$page->preHeadCloseContent .= '<link href="ppl.css" rel="stylesheet" type="text/css" />';
		$page->content .= $utils->get_include_contents('pplRegisterForm.html');
	} else {
		//create purchases
		$purchaseId = $utils->addPurchase($purchaseAttempt['pa_id'], $purchaseAttempt['pa_ppp_id'], $_SESSION['u_id']);
		error_log("purchaseId: " . $purchaseId);
		//create Membership
		$membershipId = $utils->addMembership($_SESSION['u_id'], $purchaseAttempt['pa_ppp_id']);
		error_log("MemershipId: " . $membershipId);
		//create MembershipPurchase
		$mpId = $utils->addMembershipPurchase($membershipId, $purchaseId);
		error_log("mpId: " . $mpId);
		$page->content .= 'Thanks for your purchase.  We just sent an email to' . $_SESSION['u_email'] . '.  <a href="nfl.php">Click here</a> to head over to our NFL picks page and thanks for letting us service you.';
	}
	$page->display();
	die();
} else {
	$page->content .= '<span class="error">We weren\'t able to find your purchase. Please send an email to halftimegenius@gmail.com</span><br />';
	$page->display();
}
?>